package spring.lottery.server.imp;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import spring.lottery.common.exception.ServerException;
import spring.lottery.server.PicServer;
import spring.lottery.server.exceptionCode.ServerConstantCode;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class PicServerImp implements PicServer {

    @Value("${file.local-path}")
    private String localPath;

    //项目地址
//    private String localPath = System.getProperty("user.dir");

    @Override
    public String savaPic(MultipartFile file) {

        //创建这个目录
        File dir = new File(localPath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        //getName没有后缀
        String picName = file.getOriginalFilename();
        //获取到后缀
        picName = picName.substring(picName.lastIndexOf("."));
        //给改为个新名字储存
        picName = UUID.randomUUID().toString() + picName;
        File dest = new File(dir, picName);

        try {
            //返回的是相对路径
            log.info("save pic to path: {}", dest.getPath());
            file.transferTo(dest);
            //放回储存到内存中的url

            log.info("储存的路径 {}", picName);
            //因为使用的资源映射，那么我就只需要储存图片就好了
            return picName;
        } catch (IOException e) {
            log.error("save pic error", e);
            throw new ServerException(ServerConstantCode.SAVE_IMG_REE,e.getMessage());
        }
    }

}
